package com.example.mvcdemo.list

import android.util.Log
import com.example.mvcdemo.entity.DataResult
import com.example.mvcdemo.entity.OfficeAccountBean
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import okhttp3.*
import java.io.IOException
import kotlin.math.log

class WeChatOfficeAccountApi {
    private val gson by lazy {
        GsonBuilder().serializeNulls().create()
    }

    fun loadData(callback: WeChatOfficeAccountListener) {
        callback.onLoading()
        //拿到OkhttpClient对象
        var okHttpClient = OkHttpClient()
        //构造request对象,get方式，传入接口地址
        var url = Request.Builder()
            .get()
            .url("https://wanandroid.com/wxarticle/chapters/json")
            .build()
        var newCall = okHttpClient.newCall(url)
        newCall.enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                callback.onLoadFail()
            }

            override fun onResponse(call: Call?, response: Response?) {
                var string = response?.body()?.string()
                Log.e("Tag", string)
                var result = gson.fromJson<DataResult<MutableList<OfficeAccountBean>>>(
                    string,
                    object : TypeToken<DataResult<MutableList<OfficeAccountBean>>>() {}.type
                )
                Log.e("Tag", result.toString())
                callback.onLoadSuccess(result.data)
            }
        })
    }
}

